<?php

class Emms_Form_Admin_User extends HTech_Form
{
    protected $_primary  = 'UserId';
            
    public function getValues()
    {
        $data = parent::getValues();
        if ($data['Password'] != '') $data['Password'] = md5($data['Password']);
        else unset($data['Password']);
        unset($data['Confirm']);
        return $data;
    }
    
    public function __construct() 
    {
        parent::__construct();        
        
        $this->setName('User');
        
        $this->setAttrib('title', $this->translate("User form"));
        $this->setDescription($this->translate("Edit user info or add a new one"));
        
        $userId = new Zend_Form_Element_Hidden('UserId');  
        
        $username = new Zend_Form_Element_Text('Username');
        $username->setLabel("Username")
            ->setRequired(true)
            ->addFilter('Alpha')
            ->addFilter('StringToLower')            
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addValidator('StringLength', true, array(
                'min' => 4, 
                'max' => 32, 
                'messages' => $this->translate("From %min% to %max% characters only")))
            ->addValidator('Db_NoRecordExists', true, array(
                'table' => 'users', 
                'field' => 'Username', 
                'exclude' => array('field' => 'UserId', 'value' => $this->_id),
                'messages' => $this->translate("Non valid or duplicated entry")));
        
        $password = new Zend_Form_Element_Password('Password');
        $password->setLabel("Password")
            ->addValidator('StringLength', true, array(
                'min' => 4,
                'max' => 32,
                'messages' => $this->translate("From %min% to %max% characters only")));
        
        $confirm = new Zend_Form_Element_Password('Confirm');
        $confirm->setLabel("Confirm")
            ->addValidator('Identical', true, array(
                'token' => 'Password',
                'messages' => $this->translate("Password and Confirm do not match")));
        
        $govCode = new Zend_Form_Element_Text('GovCode');
        $govCode->setLabel("Gov. code")
            ->addValidator('Regex', true, array(
                'pattern' => $this->_conf->regex->govCode->pattern,
                'messages' => sprintf($this->translate("Valid format: %s"), $this->_conf->regex->govCode->message)));  
        
        $mobilePhone = new Zend_Form_Element_Text('MobilePhone');
        $mobilePhone->setLabel("Mobile phone")
            ->addValidator('Regex', true, array(
                    'pattern' => $this->_conf->regex->tel->pattern,
                    'messages' => sprintf($this->translate("Valid format: %s"),$this->_conf->regex->tel->message)));  
        
        $homePhone = new Zend_Form_Element_Text('HomePhone');
        $homePhone->setLabel("Home phone")
            ->addValidator('Regex', true, array(
                    'pattern' => $this->_conf->regex->tel->pattern,
                    'messages' => sprintf($this->translate("Valid format: %s"),$this->_conf->regex->tel->message)));    
                            
        $address = new Zend_Form_Element_Textarea('HomeAddress');
        $address->setLabel("Home address")
            ->addFilter('Alnum', array('allowwhitespace' => true))
            ->setAttrib('rows', 2); 
        
        $birthdate = new Zend_Form_Element_Text('Birthdate');
        $birthdate->setLabel("Birthdate")
            ->setRequired(true)
            ->addValidator('Date', true, array('format' => 'yyyy-MM-dd'))
            ->addErrorMessage($this->translate("Enter a valid date. Format: YYYY-MM-DD"));
                
        $gender = new Zend_Form_Element_Select('Gender');
        $gender->setLabel("Gender")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array('Male' => $this->translate("Male"), 'Female' => $this->translate("Female"))); 
        
        $firstName = new Zend_Form_Element_Text('FirstName');
        $firstName->setLabel("First name")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 2,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));
        
        $middleName = new Zend_Form_Element_Text('MiddleName');
        $middleName->setLabel("Middle name")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 1,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));
        
        $lastName = new Zend_Form_Element_Text('LastName');
        $lastName->setLabel("Last name")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addFilter('Alpha')
            ->addValidator('StringLength', true, array(
                    'min' => 2,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));

        $secondLastName = new Zend_Form_Element_Text('SecondLastName');
        $secondLastName->setLabel("Second last name")
            ->setRequired(false)
            ->addFilter('Alpha')
            ->addValidator('StringLength', false, array(
                    'min' => 1,
                    'max' => 64,
                    'messages' => $this->translate("From %min% to %max% characters only")));

        $email = new Zend_Form_Element_Text('Email');
        $email->setLabel("Email")
            ->setRequired(true)        
            ->addValidator('EmailAddress', true)
            ->addFilter('StringToLower')
            ->addFilter('StringTrim')
            ->addErrorMessage($this->translate("Enter a valid email address"));
              
        $roleId = new Zend_Form_Element_Select('RoleId');
        $roleId->setLabel("Role")                
            ->setAttrib('size', '1')
            ->setRequired(true)
            ->addValidator('Callback', true, array(
                'callback' => array($this, 'checkRoleCallback'),
                'messages' => $this->translate("Invalid role change request")))
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + $this->_db->fetchPairs('select RoleId, Role from roles'));  
        
        $systemAccessFromDate = new Zend_Form_Element_Text('SystemAccessFromDate');
        $systemAccessFromDate->setLabel("Access granted date")
            ->setRequired(true)
            ->addValidator('Date', true, array('format' => 'yyyy-MM-dd'))
            ->addErrorMessage($this->translate("Enter a valid date. Format: YYYY-MM-DD"));
        
        $systemAccessToDate = new Zend_Form_Element_Text('SystemAccessToDate');
        $systemAccessToDate->setLabel("Access expiration date")
            ->setRequired(true)
            ->addValidator('Date', true, array('format' => 'yyyy-MM-dd'))
            ->addErrorMessage($this->translate("Enter a valid date. Format: YYYY-MM-DD"));        

        $locationId = new Zend_Form_Element_Select('LocationId');
        $locationId->setLabel("Location")                
            ->setAttrib('size', '1')
            ->setRequired(true)
            ->addValidator('Callback', true, array(
                'callback' => array($this, 'checkLocationCallback'),
                'messages' => $this->translate("Invalid location change request")))
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + $this->_db->fetchPairs('select LocationId, Name from locations'));  

        $superUserId = new Zend_Form_Element_Select('SuperUserId');
        $superUserId->setLabel("Supervisor")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + $this->_db->fetchPairs('select UserId, FullName from view_users'));  

        $maritalStatus = new Zend_Form_Element_Select('MaritalStatus');
        $maritalStatus->setLabel("Marital status")                
            ->setAttrib('size','1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option')) + array(
                'Married' => $this->translate("Married"), 
                'Single' => $this->translate("Single"), 
                'Cohabitate' => $this->translate("Cohabitate"), 
                'Divorced' => $this->translate("Divorced"), 
                'Widow' => $this->translate("Widow")));
        
        $status = new Zend_Form_Element_Select('Status');
        $status->setLabel("Status")                
            ->setAttrib('size', '1')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions(array('' => '--- ' . $this->translate('Select option'), 'Active' => $this->translate("Active"), 'Inactive' => $this->translate("Inactive")));   
                        
        $comments = new Zend_Form_Element_Textarea('Comments');
        $comments->setLabel("Comments")
            ->addFilter('Alnum', array('allowwhitespace' => true))
            ->setAttrib('rows', 2); 
        
        $submit = new Zend_Form_Element_Submit('Submit');
        $submit->setLabel("Submit")
            ->addDecorator(new HTech_Form_Decorator_Button(array('type' => 'submit'))); 
                                        
        $locationIdLock = new Zend_Form_Element_Multiselect('LnkUsersLocations');
        $locationIdLock->setLabel("Locations scope - leave all unselected for global scope.")                
            ->setAttrib('size','5')
            ->setRequired(false)
            ->addMultiOptions($this->_db->fetchPairs('select LocationId, Name from locations')); 
                                        
        $programIdLock = new Zend_Form_Element_Multiselect('LnkUsersPrograms');
        $programIdLock->setLabel("Programs scope - leave all unselected for global scope.")                
            ->setAttrib('size','5')
            ->setRequired(false)
            ->addMultiOptions($this->_db->fetchPairs('select ProgramId, Program from programs'));    
                                        
        $officerIdLock = new Zend_Form_Element_Multiselect('LnkUsersOfficers');
        $officerIdLock->setLabel("Officers scope - leave all unselected for global scope.")                
            ->setAttrib('size','5')
            ->setRequired(false)
            ->addMultiOptions($this->_db->fetchPairs('select UserId, FullName from view_officers'));         
        
        $this->setDecorators(array(array('ViewScript', array('viewScript' => 'user/_form_add.phtml'))));
        
        $this->addElements(array($username, $password, $confirm, $govCode, $birthdate, $firstName, $middleName, $lastName, $secondLastName,
            $gender, $maritalStatus, $locationId, $superUserId, $roleId, $systemAccessFromDate, $systemAccessToDate, $status, $email, $mobilePhone, $homePhone, 
            $address, $comments, $submit, $locationIdLock, $programIdLock, $officerIdLock, $userId));
    }
    
    public function checkRoleCallback($newRole, $args) 
    {
        $oldRole = $this->_db->fetchOne('select RoleId from users where UserId = ?', $args['UserId']);
        if ($oldRole != $newRole) {
            if ($oldRole == $this->_conf->role->loanofficer) {
                $bank = $this->_db->fetchOne('select BankId from banks where OfficerUserId = ?', $args['UserId']);
                $client = $this->_db->fetchOne('select ClientId from clients where OfficerUserId = ?', $args['UserId']);
                if(($bank + $client) != 0) return false;
            }
        }
        return true;    
    }
    
    public function checkLocationCallback($newLocation, $args) 
    {
        $oldLocation = $this->_db->fetchOne('select LocationId from users where UserId = ?', $args['UserId']);
        if ($oldLocation != $newLocation) {
            $oldRole = $this->_db->fetchOne('select RoleId from users where UserId = ?', $args['UserId']);
            if ($oldRole == $this->_conf->role->loanofficer) {
                $bank = $this->_db->fetchOne('select BankId from banks where OfficerUserId = ?', $args['UserId']);
                $client = $this->_db->fetchOne('select ClientId from clients where OfficerUserId = ?', $args['UserId']);
                if(($bank + $client) != 0) return false;
            }
        }
        return true;    
    }

}